from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.decorators import action       # 导入装饰器方法
from rest_framework.response import Response
from rest_framework.status import HTTP_201_CREATED
from apps.study.models import Student, Classes
from apps.study.serializers import StudentSerializer,ClassesSerializer


# class StudentViewSet(viewsets.ViewSet):
#     def list(self, request):
#         queryset = Student.objects.all()
#         # 将查询集转为json格式
#         serializer = StudentSerializer(queryset, many=True)
#         return Response(serializer.data)
#
#     def create(self,request):
#         data = request.data
#         serializer= StudentSerializer(data=data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data, status=HTTP_201_CREATED)


class StudentViewSet(viewsets.ModelViewSet):
    """
    list:
    查看全部学生信息
    create:
    新增学生信息
    retrieve:
    查看某个学生信息
    update:
    修改某个学生信息
    destroy:
    删除某个学生信息
    last:
    查看最新学生信息
    """  # 增加注释
    queryset = Student.objects.filter(is_delete=False)
    serializer_class = StudentSerializer


class ClassesViewSet(viewsets.ModelViewSet):
    """
    list:
    查看全部班级信息
    create:
    新增班级信息
    retrieve:
    查看某个班级信息
    update:
    修改某个班级信息
    destroy:
    删除某个班级信息
    last:
    查看最新班级信息
    """
    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer

    @action(methods=['get'], detail=False)  #无pk，detail为False
    def last(self,request):
        last_class = Classes.objects.filter(is_delete=False).last()
        serializer = self.get_serializer(last_class)  #  序列化
        return Response(serializer.data)